package com.cumt.websocket.client;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CountDownLatch;

/**
 * Created by caicf on 2017/1/11.
 */
@ClientEndpoint
public class WsTestClient {
    private static CountDownLatch closeLatch = new CountDownLatch(1);

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("@OnOpen - " + session);
        try {
            session.getBasicRemote().sendText("message from client");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(Session session, String msg) {
        System.out.println("@OnMessage - [" + msg + "]");
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Thanks"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(CloseReason close) {
        System.out.println("@OnClose - " + close);
//        closeLatch.countDown();
    }

    public static void main(String[] args) {
        try {
            WebSocketContainer ws = ContainerProvider.getWebSocketContainer();
            String url = "ws://127.0.0.1:5088/cumt/ws/rmu?encoding=text";
            ws.connectToServer(WsTestClient.class, new URI(url));
            closeLatch.await();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
